<?php
Yii::import('ext.gapi');

class CalculateCommand extends CConsoleCommand
{
	public function run($args){
		//0.Config
		$gapiEmail = 'jose.pompilla@itegracion.com';
		$gapiPassword = 'tacarotacaro';
		$gapiId = 57461426;
		
		$dr = Yii::app()->db->createCommand("
			SELECT value, date(value) + 1 as tomorrow FROM config WHERE id = 1
		")->queryAll();
		foreach ($dr as $item) {
			$date = $item['value'];
			$tomorrow = $item['tomorrow'];
		}
		
		echo "Recolectar Datos de Google Analytics: Inicio\n";
		//1. Recolectar Datos de Google Analytics
		Yii::app()->db->createCommand("
			UPDATE store SET date='".$date."', visits_number=0
		")->execute();
		
		$ga = new gapi($gapiEmail,$gapiPassword);
		$ga->requestReportData($gapiId,array('pagePath'),array('visitors'),array('-pagePath'),'date=='.Yii::app()->dateFormatter->format('yyyyMMdd',$date));
		foreach($ga->getResults() as $item)
		{
			Yii::app()->db->createCommand("
				UPDATE store SET visits_number=".$item->getVisitors()." WHERE name='".substr($item,1)."'
			")->execute();
			echo $item.": ".$item->getVisitors()."\n";
		}
		
		echo "Recolectar Datos de Google Analytics: Fin\n";
		
		echo "Calcular Balance: Inicio\n";
		//2. Calcular Balance
		Yii::app()->db->createCommand("
			INSERT INTO account(date, visits_number, visit_price, fee_amount, balance, store_id)
			SELECT 
				'".$date."' as date,
				s.visits_number,
				s.visit_price, 
				CASE WHEN SUM(f.amount) IS NULL THEN 0 ELSE SUM(f.amount) END as amount,
				CASE WHEN s.balance IS NULL THEN 0 ELSE s.balance END + CASE WHEN SUM(f.amount) IS NULL THEN 0 ELSE SUM(f.amount) END - (s.visits_number*s.visit_price),
				s.id
			FROM
				store s
				LEFT JOIN fee f ON f.store_id = s.id AND date(f.date_time) = '".$date."'	
			GROUP BY
				s.id, s.visit_price, s.balance, date(f.date_time)			
		")->execute();
		echo "Calcular Balance: Fin\n";
		
		echo "Actualizar Stores: Inicio\n";
		//3. Actualizar Store
		Yii::app()->db->createCommand("
			UPDATE store s, account a 
			SET 
				s.balance = a.balance, 
				s.visit_price = s.new_visit_price
			WHERE 
				a.store_id = s.id AND date(a.date) = '".$date."'
		")->execute();
		echo "Actualizar Stores: Fin\n";
		echo "Actualizar Fecha de Operacion: Inicio\n";
		//4. Actualizar Fecha de Operacion
		Yii::app()->db->createCommand("
			UPDATE config SET value='".substr($tomorrow,0,4).'-'.substr($tomorrow,4,2).'-'.substr($tomorrow,6,2)."', id=1
		")->execute();
		echo "Actualizar Fecha de Operacion: Fin\n";
	}
}